package com.cnb.telepathytalk.gcm;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class GcmMessageDatabase {
	private static final String KEY_ID = "_id";
	private static final String KEY_DATE = "date";
	private static final String KEY_TEXT = "text";

	private static final String DATABASE_NAME = "GcmMessage";
	private static final String DATABASE_TABLE = "message";
	private static final int DATABASE_VERSION = 1;

	private Context context;
	private DatabaseHelper helper;
	private SQLiteDatabase db;

	public GcmMessageDatabase(Context context) {
		this.context = context;
	}

	public GcmMessageDatabase open() {
		helper = new DatabaseHelper(context);
		db = helper.getWritableDatabase();
		return this;
	}

	public void close() {
		db.close();
		helper.close();
	}

	public ArrayList<GcmMessageDTO> getAllMessages() {
		Cursor c = db.query(DATABASE_TABLE, null, null, null, null, null, KEY_ID + " DESC");

		ArrayList<GcmMessageDTO> list = new ArrayList<GcmMessageDTO>();
		while (c.moveToNext()) {
			list.add(new GcmMessageDTO(c.getString(0), c.getString(1), c.getString(2)));
		}
		return list;
	}

	public void insert(String date, String text) {
		ContentValues cv = new ContentValues();
		cv.put(KEY_DATE, date);
		cv.put(KEY_TEXT, text);

		db.insert(DATABASE_TABLE, "", cv);
	}

	public void delete(String _id) {
		db.delete(DATABASE_TABLE, KEY_ID + "=" + _id, null);
	}

	private static class DatabaseHelper extends SQLiteOpenHelper {
		public DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(String.format("create table %s (%s integer primary key autoincrement, %s text, %s text);", DATABASE_TABLE, KEY_ID, KEY_DATE,
					KEY_TEXT));
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("drop table if exists " + DATABASE_TABLE);
			onCreate(db);
		}
	}
}